const express = require("express");
const pool = require("../pool.js");
const md5 = require("js-md5");
const { getToken, verify } = require("../utils");

const userRouter = express.Router();

module.exports = userRouter;

// 用户登录
userRouter.post("/login", (req, res, next) => {
  var uname = req.body.uname;
  var upwd = req.body.upwd;
  var sql = "select nickname,uid from user where uname=? and upwd=MD5(?)";
  pool.query(sql, [uname, upwd], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length !== 0) {
      let uid = r[0].uid;
      let token = getToken({ uid });
      // 前端要想拿到后端请求头中的数据，需要暴露它写入Access-Control-Expose-Headers
      res.setHeader("Access-Control-Expose-Headers", "authorization");
      res.setHeader("authorization", token);
      res.send({
        code: 200,
        msg: "登录成功",
        nickname: r[0].nickname,
      });
    } else {
      res.send({
        code: 201,
        msg: "用户名或密码错误",
      });
    }
  });
});

// 用户注册
userRouter.post("/register", (req, res, next) => {
  var uname = req.body.uname;
  var upwd = req.body.upwd;
  var nickname = req.body.nickname;
  var uphone = req.body.uphone;

  if (uname == "" || upwd == "" || nickname == "") {
    res.send({ code: 202, msg: "输入不能为空" });
    return;
  }
  if (!/^\w{6,10}$/.test(uname)) {
    res.send({ code: 203, msg: "用户名格式不正确" });
    return;
  }
  if (!/^\w{6,12}$/.test(upwd)) {
    res.send({ code: 204, msg: "密码格式不正确" });
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(uphone)) {
    res.send({ code: 205, msg: "手机号格式不正确" });
    return;
  }
  var illegal = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
  if (illegal.test(nickname)) {
    res.send({ code: 206, msg: "昵称非法！！" });
    return;
  }
  let sql = `insert into user(uid,uname,nickname,uphone,upwd) values(replace(UUID(),'-',''),?,?,?,MD5(?))`;
  pool.query(sql, [uname, nickname, uphone, upwd], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    res.send({ code: 200, msg: "注册成功" });
  });
});

// 检查用户名是否已被占用
userRouter.get("/checkUname", (req, res, next) => {
  let uname = req.query.uname;
  if (!uname) {
    res.send({ code: 401, msg: "uname required" });
    return;
  }
  let sql = `select uid from user where uname=?`;
  pool.query(sql, [uname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length) {
      res.send({ code: 501, msg: "用户名已被占用" });
    } else {
      res.send({ code: 200, msg: "用户名可用" });
    }
  });
});

// 检查昵称是否已被占用
userRouter.get("/checkNick", (req, res, next) => {
  let nickname = req.query.nickname;
  if (!nickname) {
    res.send({ code: 401, msg: "nickname required" });
    return;
  }
  let sql = `select uid from user where nickname=?`;
  pool.query(sql, [nickname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length) {
      res.send({ code: 501, msg: "昵称已被占用" });
    } else {
      res.send({ code: 200, msg: "昵称可用" });
    }
  });
});

// 查询个人信息
userRouter.get("/usermsg", (req, res, next) => {
  let token = req.header("authorization");
  let uid;
  verify(token, (msg) => (uid = msg.uid));
  let sql = `select uname,nickname,uphone,uimg,uemail from user where uid=?`;
  pool.query(sql, [uid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.length) {
      res.send({ code: 400, msg: "err" });
    } else {
      res.send({ msg: "ok", data: r[0] });
    }
  });
});

// 修改个人信息
userRouter.put("/update", (req, res, next) => {
  var uname = req.body.uname;
  var upwd = req.body.upwd;
  var nickname = req.body.nickname;
  var uphone = req.body.uphone;
  var uimg = req.body.uimg;
  var uemail = req.body.uemail;
  if (upwd == "" || nickname == "") {
    res.send({ code: 202, msg: "输入不能为空" });
    return;
  }
  if (!/^\w{6,12}$/.test(upwd)) {
    res.send({ code: 203, msg: "密码格式不正确" });
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(uphone)) {
    res.send({ code: 204, msg: "手机号格式不正确" });
    return;
  }
  if (uimg != "" && !/.(jpg|jpeg|png|bmp|gif)$/.test(uimg)) {
    console.log(uimg);
    res.send({ code: 205, msg: "图片格式不正确" });
    return;
  }
  if (
    uemail != "" &&
    !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(uemail)
  ) {
    res.send({ code: 206, msg: "邮箱格式不正确" });
    return;
  }
  let sql = "SELECT uid FROM user WHERE uname=?";
  pool.query(sql, [uname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      var sql2 = `update user set upwd=MD5(?) , nickname=? , uphone=? , uimg=? , uemail=? where uname=?`;
      pool.query(
        sql2,
        [upwd, nickname, uphone, uimg, uemail, uname],
        (err, r) => {
          if (err) {
            next(err);
            return;
          }
          console.log(md5(upwd));
          res.send({ code: 200, msg: "修改成功" });
        }
      );
    } else {
      res.send({ code: 201, msg: "该用户不存在" });
    }
  });
});
/** 管理员权限 */
// 删除用户
userRouter.delete("/delByName", (req, res, next) => {
  var uname = req.query.uname;
  let sql = "SELECT uid FROM user WHERE uname=?";
  pool.query(sql, [uname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      var sql2 = "DELETE FROM USER WHERE uname=?";
      pool.query(sql2, [uname], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        res.send({ code: 200, msg: "删除成功" });
      });
    } else {
      res.send({ code: 201, msg: "用户不存在" });
    }
  });
});

// 根据用户名查找用户的昵称
userRouter.get("/findByName", (req, res, next) => {
  var uname = req.query.uname;
  let sql = "SELECT nickname FROM user WHERE uname=?";
  pool.query(sql, [uname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 200, msg: "查找成功", data: r });
    } else {
      res.send({ code: 201, msg: "查找失败" });
    }
  });
});

// 查询整个用户表
userRouter.get("/findAll", (req, res, next) => {
  var page = req.query.page || 1;
  const pagesize = 10;
  var offset = (page - 1) * pagesize;
  var sql = `select count(uid) as count from user`;
  pool.query(sql, (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    var sql = "SELECT * FROM user limit ?,?";
    pool.query(sql, [offset, pagesize], (err, r) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, data: r, pagecount });
    });
  });
});
